﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using XinYiOffice.Common;
using System.IO;
using System.Data;
using XinYiOffice.Basic;
using System.Text;

namespace XinYiOffice.Web.SetUp
{
    public partial class Action : System.Web.UI.Page
    {
        public int TenantId = 0;

        public List<string> strAccountIdList = new List<string>();
        public List<string> strDesktopPlugIdList = new List<string>();
        public Dictionary<string, string> dicAccountIdList = new Dictionary<string, string>();

        public List<Model.DictionaryTable> dtList = new List<Model.DictionaryTable>();
        public List<Model.DictionaryTableValue> dtvList = new List<Model.DictionaryTableValue>();

        public int iMenuid = 0;//刚刚创建的菜单id

        protected void Page_Load(object sender, EventArgs e)
        {
            string action = xytools.url_get("action");
            if (!string.IsNullOrEmpty(action))
            {
                switch (action)
                {
                    case "regtenant":
                        RegTenant();
                        break;

                    case "init":
                        InsSql();
                        break;

                    case "clear":
                        ClearTenant();
                        break;
                }


            }

        }

        protected void ClearTenant()
        {
            TenantId = SafeConvert.ToInt(xytools.url_get("TenantId"));

            //1清除租户配置数据
            ClearTenantId(TenantId);
        }

        /// <summary>
        /// 从外部注册 租户进来
        /// </summary>
        protected void RegTenant()
        {
            string Email = xytools.form_get("Email");
            string Name = xytools.form_get("Name");
            string NameCn = xytools.form_get("NameCn");
            string NameEn = xytools.form_get("NameEn");
            string TenantGuid = xytools.form_get("TenantGuid");

            if (!xytools.DataIsNoNull(Email, Name, NameCn, TenantGuid))
            {
                //信息有缺失
                xytools.write("-4");
                return;
            }

            int ltid = LocalTenantsServer.GetLocalTenantIdByGuid(TenantGuid);
            int LocalTenantsId = 0;

            if (ltid != 0)
            {
                //已经注册
                xytools.write("-3");
                return;
            }


            Model.LocalTenants lt = new Model.LocalTenants();

            try
            {
                lt.Email = Email;
                lt.CreateTime = DateTime.Now;
                lt.CreateUserId = -99;
                lt.Name = Name;
                lt.NameCn = NameCn;
                lt.NameEn = NameEn;
                lt.State = 1;
                lt.TenantGuid = TenantGuid;

                LocalTenantsId = new BLL.LocalTenants().Add(lt);
                xytools.write(LocalTenantsId.ToString());
            }
            catch (Exception ex)
            {
                EasyLog.WriteLog(ex);
                xytools.write("-2");
            }
            finally
            {
            }

        }


        protected void InsSql()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(" <script>function SetProgress(current,itemcount,msg){");
            sb.Append("if(window.parent!=null){");
            sb.Append("parent.ThisProgress(current,itemcount,msg);}");
            sb.Append("}</script>");
            Response.Write(sb.ToString());

            TenantId = SafeConvert.ToInt(xytools.url_get("TenantId"));
            //TenantId = 2;

            //1清除租户配置数据
            ClearTenantId(TenantId); SetMsg("1", "7", "1.准备初始化");

            //2菜单
            SetMenuTreeAction(TenantId, 0); SetMsg("2", "7", "2.菜单初始化完成!");

            //3角色,用户表初始化
            SetRoleAccountAction(TenantId); SetMsg("3", "7", "3.创建用户完成!");

            //4初始化桌面
            SetDesktop(TenantId); SetMsg("4", "7", "4.初始化桌面完成!");

            //5字典数据
            SetDictionaryTable(TenantId); SetMsg("5", "7", "5.创建字典数据完成!");

            //6创建机构
            SetInstitution(TenantId); SetMsg("6", "7", "6.创建机构完成!");

            //7创建网盘
            SetSkyDrive(TenantId); SetMsg("7", "7", "7.创建网盘完成!");

            //发送邮件信息给租户email
            SendTenantAccountInfo(TenantId);

            SetMsg("7", "7", "帐号信息发送至您信箱,若未收到请联系客服");

        }

        protected void SendTenantAccountInfo(int TenantId)
        {
            Model.LocalTenants lt = LocalTenantsServer.GetLocalTenantsByTenantId(TenantId);
            if (lt == null)
            {
                return;
            }

            StringBuilder _sbGetPasswordHtml = new StringBuilder();
            StringBuilder _tb = new StringBuilder();
            _tb.Append("<table width=\"348\" border=\"0\" cellpadding=\"0\" cellspacing=\"1\" bgcolor=\"#4D84A2\">");
            _tb.Append("<tr>");
            _tb.Append("<td width=\"127\" bgcolor=\"#4D84A2\"><span style=\"color:#FFF;\">用户名</span></td>");
            _tb.Append("<td width=\"117\" bgcolor=\"#4D84A2\"><span style=\"color:#FFF;\">密码</span></td>");
            _tb.Append("<td width=\"100\" bgcolor=\"#4D84A2\"><span style=\"color:#FFF;\">角色</span></td>");
            _tb.Append(" </tr>");

            List<Model.Accounts> accountList = new BLL.Accounts().GetModelList(string.Format(" TenantId={0} ", TenantId));
            foreach (Model.Accounts acc in accountList)
            {
                _tb.Append("<tr>");
                _tb.AppendFormat("<td bgcolor=\"#FFFFFF\">{0}</td>", acc.AccountName);
                _tb.AppendFormat("<td bgcolor=\"#FFFFFF\">{0}</td>", acc.AccountPassword);
                _tb.AppendFormat("<td bgcolor=\"#FFFFFF\">{0}</td>", acc.FullName);
                _tb.Append("</tr>");
            }

            _tb.Append("</table>");

            //可以获取系统自定义模板

            #region 内部模板
            _sbGetPasswordHtml.Append("亲爱的用户,您好!").Append("<br/>");
            _sbGetPasswordHtml.Append("您的新亿云办公帐号已经初始化完成,以下是帐号和登录信息。请妥善保存,及时更改密码").Append("<br/>");
            _sbGetPasswordHtml.Append("域:<span style=\"color:red;\">{dname}</span>").Append("<br/>");
            _sbGetPasswordHtml.Append("{db}");

            _sbGetPasswordHtml.Append(@"云登录地址：http://www.xinyioffice.com/Cloud/Login.aspx").Append("<br/>");
            _sbGetPasswordHtml.Append("<hr/>").Append("<br/>");
            _sbGetPasswordHtml.Append("咨询电话:400-8600-282").Append("<br/>");
            _sbGetPasswordHtml.Append("新亿Office www.xinyioffice.com 拥有新亿云,成就小而美!").Append("<br/>");
            _sbGetPasswordHtml.Append("这封邮件由系统自动发出，请不要直接回复。").Append("<br/>");
            #endregion

            _sbGetPasswordHtml.Replace("{dname}", lt.Name);
            _sbGetPasswordHtml.Replace("{db}", _tb.ToString());

            MailTool.SendStmp(lt.Email, "新亿云办公帐号信息", _sbGetPasswordHtml.ToString(), true);
        }

        protected void SetMsg(string current_item, string countnumber, string msg)
        {
            Response.Write(string.Format("<script>SetProgress('{0}','{1}','{2}');</script>", current_item, countnumber, msg));
            Response.Flush();
        }

        /// <summary>
        /// 创建机构
        /// </summary>
        protected void SetInstitution(int TenantId)
        {
            Model.LocalTenants lt = LocalTenantsServer.GetLocalTenantsByTenantId(TenantId);
            Model.Institution ins = new Model.Institution();
            ins.CreateAccountId = -99;
            ins.CreateTime = DateTime.Now;
            ins.TenantId = TenantId;
            ins.Introduction = "机构简介...";
            ins.Logo = "机构或者公司的LOGO标识";
            ins.OrganizationName = lt.NameCn;
            ins.URL = "http://";//默认就是

            new BLL.Institution().Add(ins);
        }

        protected void SetSkyDrive(int TenantId)
        {
            Model.LocalTenants lt = LocalTenantsServer.GetLocalTenantsByTenantId(TenantId);
            string guid = lt.TenantGuid;
            string path = string.Format("~/xyo_upload/{0}", guid);

            bool isdir = Common.IO.DirectoryIsExists(path);
            if (!isdir)
            {
                System.IO.Directory.CreateDirectory(Server.MapPath(path));
                System.IO.Directory.CreateDirectory(Server.MapPath(path) + "\\空文件夹\\");
                System.IO.Directory.CreateDirectory(Server.MapPath(path) + "\\Discuss\\");
                System.IO.Directory.CreateDirectory(Server.MapPath(path) + "\\InternalLetter\\");
                System.IO.Directory.CreateDirectory(Server.MapPath(path) + "\\IssueTrackerSubsequent\\");
            }
        }

        protected void SetRoleAccountAction(int TenantId)
        {
            List<Model.Accounts> accList = new BLL.Accounts().GetModelList(string.Format(" TenantId={0} ", TenantId));
            List<Model.Accounts> accListSelect = new List<Model.Accounts>();

            #region 创建用户,附加给角色 admin

            accListSelect = accList.FindAll(delegate(Model.Accounts a) { return a.AccountName == "admin"; });
            Model.Accounts acc = new Model.Accounts();
            if (accListSelect.Count <= 0)
            {
                acc.AccountName = "admin";
                acc.AccountPassword = RandomStringGenerator.GetRandomString(6);
                acc.AccountType = 1;
                acc.CreateTime = DateTime.Now;
                acc.Email = "@";
                acc.EnName = "SuperAdministrator";
                acc.FullName = "超管";
                acc.HeadPortrait = "2";
                acc.NiceName = "超级管理员";
                acc.Sate = 1;
                acc.TenantId = TenantId;
                acc.TimeZone = 1;
                acc.Id = new BLL.Accounts().Add(acc);
            }
            else
            {
                acc = accListSelect[0];
            }
            if (!dicAccountIdList.ContainsKey("admin"))
            {
                dicAccountIdList.Add("admin", acc.Id.ToString());
            }
            #endregion

            #region 创建用户,附加给角色 sd 销售总监
            accListSelect = accList.FindAll(delegate(Model.Accounts a) { return a.AccountName == "sd"; });
            acc = new Model.Accounts();
            if (accListSelect.Count <= 0)
            {
                acc.AccountName = "sd";
                acc.AccountPassword = RandomStringGenerator.GetRandomString(6);
                acc.AccountType = 1;
                acc.CreateTime = DateTime.Now;
                acc.Email = "@";
                acc.EnName = "SalesDirector";
                acc.FullName = "销售总监";
                acc.HeadPortrait = "3";
                acc.NiceName = "销售总监";
                acc.Sate = 1;
                acc.TenantId = TenantId;
                acc.TimeZone = 1;
                acc.Id = new BLL.Accounts().Add(acc);
            }
            else
            {
                acc = accListSelect[0];
            }
            if (!dicAccountIdList.ContainsKey("sd"))
            {
                dicAccountIdList.Add("sd", acc.Id.ToString());
            }
            #endregion

            #region 创建用户,附加给角色 Project Manager 项目经理
            accListSelect = accList.FindAll(delegate(Model.Accounts a) { return a.AccountName == "pm"; });
            acc = new Model.Accounts();
            if (accListSelect.Count <= 0)
            {
                acc.AccountName = "pm";
                acc.AccountPassword = RandomStringGenerator.GetRandomString(6);
                acc.AccountType = 1;
                acc.CreateTime = DateTime.Now;
                acc.Email = "@";
                acc.EnName = "ProjectManager";
                acc.FullName = "项目经理";
                acc.HeadPortrait = "4";
                acc.NiceName = "项目经理";
                acc.Sate = 1;
                acc.TenantId = TenantId;
                acc.TimeZone = 1;
                acc.Id = new BLL.Accounts().Add(acc);
            }
            else
            {
                acc = accListSelect[0];
            }
            if (!dicAccountIdList.ContainsKey("pm"))
            {
                dicAccountIdList.Add("pm", acc.Id.ToString());
            }
            #endregion

            #region 创建用户,附加给角色 Technology Department 技术部
            accListSelect = accList.FindAll(delegate(Model.Accounts a) { return a.AccountName == "td"; });
            acc = new Model.Accounts();
            if (accList.Count <= 0)
            {
                acc.AccountName = "td";
                acc.AccountPassword = RandomStringGenerator.GetRandomString(6);
                acc.AccountType = 1;
                acc.CreateTime = DateTime.Now;
                acc.Email = "@";
                acc.EnName = "TechnologyDepartment";
                acc.FullName = "技术经理";
                acc.HeadPortrait = "5";
                acc.NiceName = "技术部";
                acc.Sate = 1;
                acc.TenantId = TenantId;
                acc.TimeZone = 1;
                acc.Id = new BLL.Accounts().Add(acc);
            }
            else
            {
                acc = accListSelect[0];
            }
            if (!dicAccountIdList.ContainsKey("td"))
            {
                dicAccountIdList.Add("td", acc.Id.ToString());
            }
            #endregion

            #region 创建用户,附加给角色 Customer Manager 客户经理
            accListSelect = accList.FindAll(delegate(Model.Accounts a) { return a.AccountName == "cm"; });
            acc = new Model.Accounts();
            if (accListSelect.Count <= 0)
            {
                acc.AccountName = "cm";
                acc.AccountPassword = RandomStringGenerator.GetRandomString(6);
                acc.AccountType = 1;
                acc.CreateTime = DateTime.Now;
                acc.Email = "@";
                acc.EnName = "CustomerManager";
                acc.FullName = "客户经理";
                acc.HeadPortrait = "6";
                acc.NiceName = "客户经理";
                acc.Sate = 1;
                acc.TenantId = TenantId;
                acc.TimeZone = 1;
                acc.Id = new BLL.Accounts().Add(acc);
            }
            else
            {
                acc = accListSelect[0];
            }
            if (!dicAccountIdList.ContainsKey("cm"))
            { dicAccountIdList.Add("cm", acc.Id.ToString()); }
            #endregion

            #region 创建用户,附加给角色 CFO 财务总监
            accListSelect = accList.FindAll(delegate(Model.Accounts a) { return a.AccountName == "cfo"; });
            acc = new Model.Accounts();
            if (accListSelect.Count <= 0)
            {
                acc.AccountName = "cfo";
                acc.AccountPassword = RandomStringGenerator.GetRandomString(6);
                acc.AccountType = 1;
                acc.CreateTime = DateTime.Now;
                acc.Email = "@";
                acc.EnName = "CFO";
                acc.FullName = "财务总监";
                acc.HeadPortrait = "7";
                acc.NiceName = "财务总监";
                acc.Sate = 1;
                acc.TenantId = TenantId;
                acc.TimeZone = 1;
                acc.Id = new BLL.Accounts().Add(acc);
            }
            else
            {
                acc = accListSelect[0];
            }
            if (!dicAccountIdList.ContainsKey("cfo"))
            {
                dicAccountIdList.Add("cfo", acc.Id.ToString());
            }
            #endregion


            Dictionary<string, string> dicNewPermissions = new Dictionary<string, string>();
            List<Model.Permissions> perList = new BLL.Permissions().GetModelList(string.Format("TenantId={0}", 1));
            #region 初始化权限标签
            foreach (Model.Permissions p in perList)
            {
                p.TenantId = TenantId;
                p.CreateTime = DateTime.Now;
                p.RefreshTime = DateTime.Now;

                int pid = new BLL.Permissions().Add(p);
                if (!dicNewPermissions.ContainsKey(p.Sign))
                {
                    dicNewPermissions.Add(p.Sign, pid.ToString());
                }

            }
            #endregion

            Dictionary<string, string> dicNewRoles = new Dictionary<string, string>();
            List<Model.Roles> rolList = new BLL.Roles().GetModelList(string.Format(" TenantId={0} ", 1));
            #region 初始化角色
            foreach (Model.Roles _rol in rolList)
            {
                _rol.TenantId = TenantId;
                _rol.CreateTime = DateTime.Now;
                _rol.RefreshTime = DateTime.Now;

                int rid = new BLL.Roles().Add(_rol);
                if (!dicNewRoles.ContainsKey(_rol.Name))
                {
                    dicNewRoles.Add(_rol.Name, rid.ToString());
                }
            }
            #endregion

            List<Model.RolePermissions> rpList = new BLL.RolePermissions().GetModelList(string.Format(" TenantId={0} ", 1));
            Model.Permissions per = new Model.Permissions();
            Model.Roles r = new Model.Roles();
            #region 角色权限关系表
            foreach (Model.RolePermissions rp in rpList)
            {
                rp.TenantId = TenantId;
                rp.CreateTime = DateTime.Now;
                rp.RefreshTime = DateTime.Now;
                rp.CreateAccountId = -99;

                per = perList.Find(delegate(Model.Permissions _p) { return (_p.Id == SafeConvert.ToInt(rp.PermissionId)); });
                r = rolList.Find(delegate(Model.Roles _r) { return (_r.Id == rp.RoleId); });
                if (r == null || per == null)
                {
                    continue;
                }
                string newpid = string.Empty;
                string newrid = string.Empty;

                dicNewPermissions.TryGetValue(per.Sign, out newpid);
                dicNewRoles.TryGetValue(r.Name, out newrid);

                rp.RoleId = SafeConvert.ToInt(newrid);
                rp.PermissionId = SafeConvert.ToInt(newpid);
                new BLL.RolePermissions().Add(rp);
            }
            #endregion


            #region 为账户配置权限
            foreach (KeyValuePair<string, string> kvp in dicAccountIdList)
            {
                string rolname = kvp.Key;
                int accountid = SafeConvert.ToInt(kvp.Value);
                string rolId = string.Empty;

                switch (rolname)
                {
                    case "admin":
                        dicNewRoles.TryGetValue("超级管理员", out rolId);
                        break;

                    case "cfo":
                        dicNewRoles.TryGetValue("财务总监", out rolId);
                        break;

                    case "cm":
                        dicNewRoles.TryGetValue("客户经理", out rolId);
                        break;

                    case "td":
                        dicNewRoles.TryGetValue("技术部", out rolId);
                        break;

                    case "pm":
                        dicNewRoles.TryGetValue("项目经理", out rolId);
                        break;

                    case "sd":
                        dicNewRoles.TryGetValue("销售总监", out rolId);
                        break;

                }

                Model.AccountRoles ar = new Model.AccountRoles();
                ar.AccountId = SafeConvert.ToInt(accountid);
                ar.CreateAccountId = -99;
                ar.CreateTime = DateTime.Now;
                ar.RoleId = SafeConvert.ToInt(rolId);
                ar.TenantId = TenantId;

                new BLL.AccountRoles().Add(ar);
            }
            #endregion

            SystemJournalServer.SetSysLog("租户初始化_角色", -99, TenantId);
        }

        List<Model.MenuTree> mtList;
        Dictionary<string, string> dicMenuTree = new Dictionary<string, string>();

        protected void SetMenuTreeAction(int TenantId, int MenuTreePid)
        {
            if (mtList == null || mtList.Count < 0)
            {
                mtList = new BLL.MenuTree().GetModelList(string.Format(" TenantId={0} ", 1));
            }

            List<Model.MenuTree> mtMenuTreeCurrent = mtList.FindAll(delegate(Model.MenuTree _mt) { return (_mt.MenuTreeId == MenuTreePid); }); ;

            foreach (Model.MenuTree mt in mtMenuTreeCurrent)
            {
                mt.TenantId = TenantId;
                mt.CreateTime = DateTime.Now;
                mt.CreateAccountId = -99;
                int pid = SafeConvert.ToInt(mt.MenuTreeId);

                if (pid != 0)
                {
                    #region 获取或者创建父级ID
                    Model.MenuTree _m = mtList.Find(delegate(Model.MenuTree _mt) { return _mt.Id == pid; });
                    string newid = string.Empty;
                    int inewid = 0;
                    if (dicMenuTree.ContainsKey(_m.Guid))
                    {
                        dicMenuTree.TryGetValue(_m.Guid, out newid);
                        inewid = SafeConvert.ToInt(newid);
                    }
                    else
                    {
                        Model.MenuTree _new_m = new Model.MenuTree();
                        _new_m = _m;
                        _new_m.CreateTime = DateTime.Now;
                        _new_m.CreateAccountId = -99;
                        _new_m.TenantId = TenantId;
                        inewid = new BLL.MenuTree().Add(_new_m);
                    }
                    #endregion

                    mt.MenuTreeId = inewid;
                }
                else
                {
                    mt.MenuTreeId = 0;
                }

                if (!dicMenuTree.ContainsKey(mt.Guid))
                {
                    int mid = new BLL.MenuTree().Add(mt);
                    if (!string.IsNullOrEmpty(mt.ChainedAddress))
                    {
                        Model.MenuTree upmt = new BLL.MenuTree().GetModel(mid);
                        upmt.ChainedAddress = upmt.ChainedAddress.Replace(SafeConvert.ToString(mt.Id), SafeConvert.ToString(mid));
                        new BLL.MenuTree().Update(upmt);

                        //mt.ChainedAddress = mt.ChainedAddress.Replace(SafeConvert.ToString(mt.Id), SafeConvert.ToString(mid));
                        //new BLL.MenuTree().Update(mt);
                    }

                    dicMenuTree.Add(mt.Guid, mid.ToString());
                }

                bool isclass = IsMenuTreeClass(mt.Id);
                if (isclass)
                {
                    SetMenuTreeAction(TenantId, mt.Id);
                }

            }
        }

        /// <summary>
        /// 是否有子集
        /// </summary>
        /// <param name="MenuTreeId"></param>
        /// <returns></returns>
        protected bool IsMenuTreeClass(int MenuTreeId)
        {
            List<Model.MenuTree> _mtList = mtList.FindAll(delegate(Model.MenuTree mt) { return (mt.MenuTreeId == MenuTreeId); });
            bool t = false;
            if (_mtList != null && _mtList.Count > 0)
            {
                t = true;
            }

            return t;
        }

        protected void SetDictionaryTable(int TenantId)
        {
            dtList = new BLL.DictionaryTable().GetModelList(string.Format(" TenantId={0} ", 1));
            dtvList = new BLL.DictionaryTableValue().GetModelList(string.Format(" TenantId={0} ", 1));

            foreach (Model.DictionaryTable dt in dtList)
            {
                int _DictionaryTableId = 0;
                List<Model.DictionaryTable> _dtList = new BLL.DictionaryTable().GetModelList(string.Format(" TenantId={0} and Name='{1}' ", TenantId, dt.Name));
                if (_dtList != null && _dtList.Count > 0)
                {
                    _DictionaryTableId = _dtList[0].Id;
                }
                else
                {
                    dt.TenantId = TenantId;
                    dt.CreateTime = DateTime.Now;
                    _DictionaryTableId = new BLL.DictionaryTable().Add(dt);
                }

                List<Model.DictionaryTableValue> _dtvList = dtvList.FindAll(delegate(Model.DictionaryTableValue dtv) { return dtv.DictionaryTableId == dt.Id; });
                //找出一个键下的值
                foreach (Model.DictionaryTableValue dtv in _dtvList)
                {
                    dtv.TenantId = TenantId;
                    dtv.CreateTime = DateTime.Now;
                    dtv.DictionaryTableId = _DictionaryTableId;

                    new BLL.DictionaryTableValue().Add(dtv);
                }
            }
        }



        protected void SetDesktop(int TenantId)
        {
            List<Model.DesktopPlug> DesktopPlugList = new BLL.DesktopPlug().GetModelList(string.Format(" TenantId={0} ", 1));

            foreach (Model.DesktopPlug dp in DesktopPlugList)
            {
                Model.DesktopPlug _dp = new Model.DesktopPlug();
                _dp.Description = dp.Description;
                _dp.LoadAddress = dp.LoadAddress;
                _dp.Name = dp.Name;
                _dp.TenantId = TenantId;

                DataSet dsDesktopPlug = DbHelperSQL.Query(string.Format("SELECT * FROM [DesktopPlug] where Name='{0}' and TenantId={1} ", _dp.Name, TenantId));
                if (dsDesktopPlug != null && dsDesktopPlug.Tables[0].Rows.Count > 0)
                {
                    _dp.Id = SafeConvert.ToInt(dsDesktopPlug.Tables[0].Rows[0]["Id"]);
                }
                else
                {
                    _dp.Id = new BLL.DesktopPlug().Add(_dp);
                }

                //strDesktopPlugIdList.Add(_dp.Id.ToString());

                //匹配账户与桌面
                foreach (KeyValuePair<string, string> accid in dicAccountIdList)
                {
                    DataSet dsDesktop = DbHelperSQL.Query(string.Format("SELECT * FROM [Desktop] where AccountId={0} and DesktopPlugId={1} and TenantId={2} ", accid.Value, _dp.Id, TenantId));
                    if (dsDesktop != null && dsDesktop.Tables[0].Rows.Count > 0)
                    {

                    }
                    else
                    {
                        Model.Desktop _des = new Model.Desktop();
                        _des.AccountId = SafeConvert.ToInt(accid.Value);
                        _des.CreateTime = DateTime.Now;
                        _des.DesktopPlugId = _dp.Id;
                        _des.Sort = 0;
                        _des.TenantId = TenantId;
                        new BLL.Desktop().Add(_des);
                    }
                }
            }


        }

        protected void ClearTenantId(int TenantId)
        {
            List<string> strSql = new List<string>();
            strSql.Add(string.Format("DELETE FROM [AccountRoles] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [Accounts] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [Roles] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [RolePermissions] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [Permissions] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [Desktop] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [DesktopPlug] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [MenuTree] where TenantId={0}", TenantId));

            strSql.Add(string.Format("DELETE FROM [AdvicePayment] where TenantId={0}", TenantId));


            strSql.Add(string.Format("DELETE FROM [BankAccount] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [BankAccountDetails] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [ClientInfo] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [ClientInfoExpand] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [ClientInfoExpandValue] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [ClientLiaisons] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [ClientTracking] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [CustomDisplay] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [CustomerService] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [Department] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [Desktop] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [DesktopPlug] where TenantId={0}", TenantId));

            strSql.Add(string.Format("DELETE FROM [DesktopShortcut] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [DictionaryTable] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [DictionaryTableValue] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [Discuss] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [DiscussClass] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [InternalLetter] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [InternalReceiver] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [IssueTracker] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [IssueTrackerSubsequent] where TenantId={0}", TenantId));

            strSql.Add(string.Format("DELETE FROM [IssueTrackerTypes] where TenantId={0}", TenantId));
            //strSql.Add(string.Format("DELETE FROM [LocalTenants] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [MakeCollections] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [MarketingPlan] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [MenuTree] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [OfficeWorker] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [PayrollControl] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [PermissionCategories] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [Permissions] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [Programme] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [ProgrammeMembers] where TenantId={0}", TenantId));

            strSql.Add(string.Format("DELETE FROM [ProjectInfo] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [ProjectMembers] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [ProjectRoles] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [ProjectTypes] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [ReimbursementExpenses] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [ResAttachment] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [ResFolder] where TenantId={0}", TenantId));

            strSql.Add(string.Format("DELETE FROM [SalesOpportunities] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [SearchConfig] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [SearchConfigItem] where TenantId={0}", TenantId));

            strSql.Add(string.Format("DELETE FROM [SearchDataSoure] where TenantId={0}", TenantId));
            strSql.Add(string.Format("DELETE FROM [SystemJournal] where TenantId={0}", TenantId));


            DbHelperSQL.ExecuteSqlTran(strSql);

        }
    }
}